/**
 * Created by easy on 15/5/11.
 */
var vars = {}, basic = {}, util = {}, common = {}, service = {};

(function () {
    common.checkbox = function (touchObj) {
        var checkbox = $(touchObj).find('.checkbox');
        if (checkbox.hasClass("active")) {
            checkbox.removeClass("active")
        } else {
            checkbox.addClass("active")
        }
    };
    common.radio = function (touchObj) {
        var radio = $(touchObj).find('.checkbox');
        if (radio.hasClass("active") == false) {
            $(touchObj).siblings().find('.checkbox').removeClass("active");
            radio.addClass("active")
        }
    };
    vars.scrollstatus = 0;

    // 分页
    common.morePage = function (options) {
        var execPagging = false;
        var dataLength = options.dataLength,
            scrollContainer = options.scrollContainer,
            callback = options.callback,
            loadingNoticeObj = options.loadingNoticeObj == undefined ? $(".mc-scroll-loading") : options.loadingNoticeObj,
            currentPageVarName;
        if (options.mode != "timeStamp") {
            currentPageVarName = options.currentPageVarName == undefined ? "currentPage" : options.currentPageVarName;
            vars[currentPageVarName] += 1;
        }
        scrollContainer.off("scroll").on("scroll", function () {//监听列表滚动事件
            var scrolltop = scrollContainer.scrollTop();//显示区域到顶部距离
            if (scrolltop <= 0) {//页面滚动为负值
                vars.scrollstatus = 0
            }
            if (scrolltop > 0) {//页面滚动为正值
                vars.scrollstatus = 1;
            }
            var innerheight = scrollContainer.innerHeight();//显示区域高度
            var scrollheight = scrollContainer[0].scrollHeight;//整个区域高度
            if ((parseInt(scrolltop) + parseInt(innerheight) >= scrollheight - 25) && execPagging == false) { //滑动到最底部时
                //scrollContainer.off('scroll');
                if (dataLength == vars.pageSize) {
                    callback();
                    //console.log("调用")
                }
                execPagging = true;
            }
        });
        if (dataLength < vars.pageSize) {
            var pomptlabel;
            var judge;
            if (options.mode == "timeStamp") {
                judge = (vars.lastTimeStamp == null)
            } else {
                judge = (vars[currentPageVarName] == 2)
            }
            //alert(judge);
            if (judge) {
                if (dataLength == 0) {
                    pomptlabel = "";
                    scrollContainer.siblings(".mc-nodata").fadeIn();
                    scrollContainer.find(".mc-nodata").fadeIn();
                    loadingNoticeObj.hide();
                } else {
                    pomptlabel = "";
                    scrollContainer.siblings(".mc-nodata").hide();
                    scrollContainer.find(".mc-nodata").hide();
                    loadingNoticeObj.hide();

                }
            } else {
                //alert(options.mode);
                if (options.mode == "timeStamp") {
                    pomptlabel = "";
                    loadingNoticeObj.hide();
                } else {
                    pomptlabel = "已无更多"
                }

            }
            loadingNoticeObj.find(".mc-scroll-pomptlabel").html(pomptlabel);
        } else if(dataLength == vars.pageSize){
            //alert(dataLength)
            loadingNoticeObj.show().find(".mc-scroll-pomptlabel").html("加载中");
        }
    };
    common.initScrollList = function (options) {
        var loadingNoticeObj = options.loadingNoticeObj == undefined ? $(".mc-scroll-loading") : options.loadingNoticeObj,
            scrollContainer = options.scrollContainer;
        if (options.mode == "timeStamp") {
            var lastTimeStampName = options.lastTimeStampName;
            vars[lastTimeStampName] = null;
        } else {
            var currentPageVarName = options.currentPageVarName == undefined ? "currentPage" : options.currentPageVarName;
            vars[currentPageVarName] = 1;
        }
        loadingNoticeObj.hide().find(".mc-scroll-pomptlabel").html("");
        scrollContainer.siblings(".mc-nodata").hide();
    };

    // 监听页面事件
    basic.eventNotification = function (data) {
        //alert(JSON.stringify(data))
        try {
            data = JSON.parse(data);
        } catch (e) {
        }
        switch (data.type) {
            case "ajaxStarted":
                util.ajaxStarted(data.ajaxID, data.matchIDs);
                break;
            case "ajaxCompleted":
                util.ajaxCompleted(data.ajaxID, data.result, data.matchIDs);
                break;
            case "leftButtonEvent":
                util.leftButtonEventCallback();
                break;
            case "rightButtonEvent":
                util.rightButtonEventCallback();
                break;
        }
    };

    // 根据类型显示提交结果
    common.changeAjaxBadgeStatus = function (type, ajaxItem, table, id, callback) {
        var badgeObj = ajaxItem.find(".ajax-status");
        switch (type) {
            case 1:
                badgeObj.removeClass("textcolor-danger mc-responseicon textcolor-success")
                    .addClass("textcolor-main")
                    .html("上传中").show().off("click");
                break;
            case 2:
                badgeObj.removeClass("textcolor-danger mc-responseicon textcolor-main")
                    .addClass("textcolor-success")
                    .html("上传成功").show()
                    .fadeOut(800, callback).off("click");
                break;
            case 3:
                badgeObj.removeClass("textcolor-main textcolor-success")
                    .addClass("textcolor-danger mc-responseicon")
                    .html("上传失败<br>点击重试")
                    .on("click", function () {
                        var touchObj = ajaxItem.find(".ajax-status")[0];
                        if (table == "ajax") {
                            common.execUploadAjaxTask(touchObj, [id]);
                        } else if (table == "order") {
                            util.findThisOrdersFailedTask(touchObj, id)
                        } else if (table == "abnormal") {
                            util.findThisAbnormalsFailedTask(touchObj, id)
                        } else if (table == "abnormalRemark") {
                            util.findThisAbnormalsFailedTask(touchObj, id)
                        } else if (table == "orderRemark") {
                            util.findThisRemarkFailedTask(touchObj, id)
                        } else if (table == "process") {
                            util.findThisProcessFailedTask(touchObj, id)
                        }
                    });
                break;
        }
    };

    // 重新上传
    common.execUploadAjaxTask = function (touchObj, ajaxIDs) {
        if ($(touchObj).hasClass("textcolor-danger")) {
            var title = "是否重新上传？";
            mc.confirm(title, function () {
                mc.uploadAjaxTask(ajaxIDs)
            })
        }
    };

    // 获取图片下载进度
    common.changePhotosProgress = function () {
        var getPhotosProgressCallback = function (data) {
            //alert(JSON.stringify(data));
            $(".imgprogress").hide();
            if (data == "{}") {
                clearInterval(getProgress);
                return
            }
            data = JSON.parse(data);
            for (var key in data) {
                var imgID = key.replace("96x96_", "").split(".")[0];
                $("#" + imgID).parent().find(".imgprogress").html(data[key] + "%").show().css("height", (100 - data[key]) + "%");
            }
        };
        var getProgress = setInterval(function () {
            mc.getPhotosProgress(getPhotosProgressCallback)
        }, 500)
    };

    // 显示图片
    common.showPhotos = function (data) {
        //alert(JSON.stringify(data))
        var photosArray = [];
        data = (data == null || data == undefined || data == "" ? [] : data);
        var length = data.length;
        for (var i = 0; i < length; i++) {
            if (data[i].attachment != null && data[i].attachment != undefined && data[i].attachment != "null") {
                var photos = JSON.parse(data[i].attachment);
                if (photos != undefined && photos != null && photos != "" && photos != "[]" && photos != []) {
                    photosArray = $.merge(photosArray, photos);
                }
            }
            if (data[i].replyList != null && data[i].replyList != undefined && data[i].replyList != "null" && data[i].replyList != "") {
                var subLength = data[i].replyList.length;
                for (var j = 0; j < subLength; j++) {
                    var subPhotos = data[i].replyList[j].attachment;
                    if (subPhotos != undefined && subPhotos != "" && subPhotos != "[]" && subPhotos != [] && subPhotos != "null") {
                        var dataSubPhotos = [];
                        dataSubPhotos = (JSON.parse(subPhotos));
                        photosArray = $.merge(photosArray, dataSubPhotos);
                    }
                }
            }
        }
        var photosArrayLength = photosArray.length;
        var thumbnailPhotos = '';
        for (var i = 0; i < photosArrayLength; i++) {
            if(photosArray[i].indexOf("thumbnail") < 0) {
                thumbnailPhotos += ("'96x96_" + photosArray[i] + "',");
            } else {
                thumbnailPhotos += ("'" + photosArray[i] + "',");
            }
        }
        thumbnailPhotos = thumbnailPhotos.substr(0, thumbnailPhotos.length - 1);
        //alert(thumbnailPhotos)
        //alert("select * from T_ImgFilePaths where FImgFileKey in (" + thumbnailPhotos + ");");
        mc.execSQL("select * from T_ImgFilePaths where FImgFileKey in (" + thumbnailPhotos + ");", [], function (data) {
            //alert(JSON.stringify(data))
            data = (data == null || data == undefined || data == "" ? [] : data);
            //var shouldDownloadPhotos = [];
            for (var i = 0; i < photosArrayLength; i++) {
                var hasDownload = false;
                for (var j = 0; j < data.length; j++) {
                    if (("96x96_" + (photosArray[i])) == data[j].FImgFileKey || photosArray[i] == data[j].FImgFileKey) {
                        //alert(1111)
                        hasDownload = true;
                        var id = data[j].FImgFileKey.replace("96x96_", "");
                        $("#" + id.split(".")[0]).attr("src", data[j].FImgFilePath);
                    }
                }
                if (hasDownload == false) {
                    //shouldDownloadPhotos.push(photosArray[i].thumbnailFileKey)
                    //"thumbnail50x50" + photosArray[i].split(".")[0]
                    var key = "";
                    if(photosArray[i].indexOf("thumbnail") < 0) {
                        key = "96x96_" + photosArray[i];
                    } else {
                        key = photosArray[i];
                    }
                    mc.downloadPhoto(key, function (data) {
                        //alert(JSON.stringify(data))
                        if (data.result == true) {
                            var id = data.fileID.replace("96x96_", "");
                            $("#" + id.split(".")[0]).attr("src", data.filePath);
                        }
                    })
                }
            }
            //alert(JSON.stringify(shouldDownloadPhotos))
            //mc.downloadPhoto(shouldDownloadPhotos,function(data){
            //    alert(JSON.stringify(data))
            //})
        });
    };

    // 显示订单示意图
    common.showOrderPhotos = function (data) {
        var photosArray = [];
        data = (data == null || data == undefined || data == "" ? [] : data);
        var length = data.length;

        for (var i = 0; i < length; i++) {
            if (data[i].orderAttachment != null && data[i].orderAttachment != undefined && data[i].orderAttachment != "null") {
                var photos = data[i].orderAttachment;
                if (photos != undefined && photos != "" && photos != null && photos != "[]" && photos != []) {
                    var dataPhotos = [];
                    try {
                        dataPhotos = JSON.parse(photos);
                    } catch (e) {
                    }
                    photosArray = $.merge(photosArray, dataPhotos);
                }
            }
        }
        var photosArrayLength = photosArray.length;
        var thumbnailPhotos = '';
        for (var i = 0; i < photosArrayLength; i++) {
            thumbnailPhotos += ("'320x240_" + (photosArray[i]) + "',");
        }
        thumbnailPhotos = thumbnailPhotos.substr(0, thumbnailPhotos.length - 1);
        mc.execSQL("select * from T_ImgFilePaths where FImgFileKey in (" + thumbnailPhotos + ")", [], function (data) {
            //alert(JSON.stringify(data))
            data = (data == null || data == undefined || data == "" ? [] : data);
            //var shouldDownloadPhotos = [];
            for (var i = 0; i < photosArrayLength; i++) {
                var hasDownload = false;
                for (var j = 0; j < data.length; j++) {
                    if (("320x240_" + (photosArray[i])) == data[j].FImgFileKey) {
                        hasDownload = true;
                        var id = data[j].FImgFileKey.replace("320x240_", "");
                        $("#" + id.split(".")[0]).attr("src", data[j].FImgFilePath);
                    }
                }
                if (hasDownload == false) {
                    //shouldDownloadPhotos.push(photosArray[i].thumbnailFileKey)
                    //"thumbnail50x50" + photosArray[i].split(".")[0]
                    mc.downloadPhoto("320x240_" + photosArray[i], function (data) {
                        //alert(JSON.stringify(data))
                        if (data.result == true) {
                            var id = data.fileID.replace("320x240_", "");
                            $("#" + id.split(".")[0]).attr("src", data.filePath);
                        }
                    })
                }
            }
            //alert(JSON.stringify(shouldDownloadPhotos))
            //mc.downloadPhoto(shouldDownloadPhotos,function(data){
            //    alert(JSON.stringify(data))
            //})
        });
    }

    // 显示第一张订单示意图
    common.showFirstOrderPhotos = function (data, currPage) {
        var photosArray = [];
        data = (data == null || data == undefined || data == "" ? [] : data);
        var length = data.length;
        currPage = currPage == undefined ? 1 : parseInt(currPage);
        for (var i = 0; i < length; i++) {
            if (data[i].orderAttachment != null && data[i].orderAttachment != undefined && data[i].orderAttachment != "null") {
                var photos = data[i].orderAttachment;
                if (photos != undefined && photos != "" && photos != null && photos != "[]" && photos != []) {
                    var dataPhotos = [];
                    try {
                        dataPhotos.push(photos.split(".")[0] + "_" + (i + ((parseInt(currPage) - 1) * 10)) + "." + photos.split(".")[1]);
                    } catch (e) {
                    }
                    photosArray = $.merge(photosArray, dataPhotos);
                }
            }
        }
        var photosArrayLength = photosArray.length;
        var thumbnailPhotos = '';
        for (var i = 0; i < photosArrayLength; i++) {
            thumbnailPhotos += ("'320x240_" + (photosArray[i].split("_")[0] + "." + photosArray[i].split(".")[1]) + "',");
        }
        thumbnailPhotos = thumbnailPhotos.substr(0, thumbnailPhotos.length - 1);
        mc.execSQL("select * from T_ImgFilePaths where FImgFileKey in (" + thumbnailPhotos + ")", [], function (data) {
            //alert(JSON.stringify(data))
            data = (data == null || data == undefined || data == "" ? [] : data);
            //var shouldDownloadPhotos = [];
            for (var i = 0; i < photosArrayLength; i++) {
                var checkPhoto = function (index) {
                    var hasDownload = false;
                    for (var j = 0; j < data.length; j++) {
                        if (("320x240_" + photosArray[index].split("_")[0] + "." + photosArray[index].split(".")[1]) == data[j].FImgFileKey) {
                            hasDownload = true;
                            var id = data[j].FImgFileKey.replace("320x240_", "");
                            $("#" + photosArray[index].split(".")[0]).attr("src", data[j].FImgFilePath);
                        }
                    }
                    if (hasDownload == false) {
                        //shouldDownloadPhotos.push(photosArray[i].thumbnailFileKey)
                        //"thumbnail50x50" + photosArray[i].split(".")[0]
                        mc.downloadPhoto("320x240_" + photosArray[index].split("_")[0] + "." + photosArray[index].split(".")[1], function (data) {
                            //alert(JSON.stringify(data))
                            if (data.result == true) {
                                var id = data.fileID.replace("320x240_", "");
                                $("#" + photosArray[index].split(".")[0]).attr("src", data.filePath);
                            }
                        })
                    }
                }
                checkPhoto(i);
            }
            //alert(JSON.stringify(shouldDownloadPhotos))
            //mc.downloadPhoto(shouldDownloadPhotos,function(data){
            //    alert(JSON.stringify(data))
            //})
        });
    }


    /*common.showPhotosByIndex = function (data, jsonPK, currIndex) {
     //var data = vars.ractiveAbnormalDetail.data.ractiveData;
     var photoKeyArray = [];
     for(var i = 0; i < data.length;i++){
     if(data[i].jsonPK == jsonPK){
     var photosData = JSON.parse(data[i].attachmentEdit ? data[i].attachmentEdit : data[i].attachment);
     for(var j = 0;j < photosData.length;j++){
     photoKeyArray.push(photosData[j].originalFileKey);
     }
     }
     }
     mc.showPhotosByIndex(photoKeyArray, currIndex);
     }
     common.showReplyPhotosByIndex = function (data, jsonPK, currIndex) {
     //var data = vars.ractiveAbnormalDetail.data.ractiveData;
     var photoKeyArray = [];
     for(var i = 0; i < data.length;i++){
     for(var j = 0; j < data[i].replyList.length ; j++) {
     if (data[i].replyList[j].jsonPK == jsonPK) {
     var photosData = JSON.parse(data[i].replyList[j].attachment);
     for (var z = 0; z < photosData.length; z++) {
     photoKeyArray.push(photosData[z].originalFileKey);
     }
     }
     }
     }
     mc.showPhotosByIndex(photoKeyArray, currIndex);
     }*/

    // 显示某一张订单示意图缩略图的大图
    common.showOrderPhotoByIndex = function (attachment, currIndex) {
        //var data = vars.ractiveAbnormalDetail.data.ractiveData;
        var callback = function (data) {
            if(mc.device == iOS && !data.result) {
                mc.notification(data.error, "Info");
            }
        }
        mc.showPhotosByIndex(attachment, currIndex, callback);
    }

    // 显示某一张缩略图的大图
    common.showPhotosByIndex = function (attachment, currIndex) {
        //var data = vars.ractiveAbnormalDetail.data.ractiveData;
        var photoKeyArray = [];
        var photosData = JSON.parse(attachment);
        for (var j = 0; j < photosData.length; j++) {
            photoKeyArray.push(photosData[j]);
        }
        var callback = function (data) {
            if(mc.device == iOS && !data.result) {
                mc.notification(data.error, "Info");
            }
        }
        mc.showPhotosByIndex(photoKeyArray, currIndex, callback);
    }

    common.showOrderPhotosByIndex = function (attachment, currIndex) {
        //var data = vars.ractiveAbnormalDetail.data.ractiveData;
        var photoKeyArray = [];
        var photosData = JSON.parse(attachment);
        for (var j = 0; j < photosData.length; j++) {
            //photoKeyArray.push("original" + photosData[z]);
            photoKeyArray.push(photosData[j]);
        }
        var callback = function (data) {
            //alert(JSON.stringify(data))
        }
        mc.showPhotosByIndex(photoKeyArray, currIndex, callback);
    }

    // 显示回复缩略图大图
    common.showReplyPhotosByIndex = function (attachment, currIndex) {
        //var data = vars.ractiveAbnormalDetail.data.ractiveData;
        var photoKeyArray = [];
        var photosData = JSON.parse(attachment);
        for (var z = 0; z < photosData.length; z++) {
            //photoKeyArray.push(photosData[z].originalFileKey);
            //photoKeyArray.push("original" + photosData[z]);
            photoKeyArray.push(photosData[z]);
        }
        var showPhotoByIndexCallBack = function (data) {
            if(mc.device == iOS && !data.result) {
                mc.notification(data.error, "Info");
            }
        };
        mc.showPhotosByIndex(photoKeyArray, currIndex, showPhotoByIndexCallBack);
    };

    /*
     作用：实现HashTable功能
     示例：
     var ht = new HashTable();
     ht.Add("key0", "value0");
     ht.Add("key1", ["a","b","c"]);
     ht.Add("key2", "value2");
     ht.Del("key0");

     alert("共有："+ht.Count()+"条数据");
     alert("key1是否存在："+ht.Contains("key1"));
     alert("key1的索引0值为："+ht.Get("key1")[0]);
     */
    /*common.HashTable = function () {
        this._hash = new Object();
        this.Add = function (key, value) {
            if (typeof (key) != "undefined" && (this.Contains(key) == false)) {
                this._hash[key] = value;
                return true;
            }
            return false;
        }
        this.GetByIndex = function (i) {
            var n = 0;
            for (var k in this._hash) {
                if (n == i) {
                    return {'key': k, 'value': this._hash[k]};
                }
                n++;
            }
        }
        this.Del = function (key) {
            delete this._hash[key];
        }
        this.Count = function () {
            var i = 0;
            for (var k in this._hash) {
                i++;
            }
            return i;
        }
        this.Get = function (key) {
            return this._hash[key];
        }
        this.Contains = function (key) {
            return typeof(this._hash[key]) != "undefined";
        }
        this.Clear = function () {
            for (var k in this._hash) {
                delete this._hash[k];
            }
        }
    }*/

})();